﻿/**
<code>
  <author name="Zealic" email="zealic(at)gmail.com" type="Creator"/>
</code>
**/
using System;
using System.Collections.Generic;
using System.Reflection;


namespace Zealib.Transform
{
    /// <summary>
    /// Assembly transformer factory.
    /// </summary>
    public class AssemblyTransformerFactory : ITransformerFactory
    {
        private readonly IList<Type> _TransformerTypes = new List<Type>();

        public AssemblyTransformerFactory(string assemblyFile)
            : this(Assembly.LoadFrom(assemblyFile))
        {
        }

        public AssemblyTransformerFactory(Assembly assembly)
        {
            if (assembly == null) throw new ArgumentNullException("assembly");
            Assembly = assembly;

            foreach (Type type in Assembly.GetTypes())
            {
                if (type.IsClass &&
                    !type.IsAbstract &&
                    !type.IsInterface &&
                    !type.IsGenericTypeDefinition)
                {
                    Type findedFace = Array.Find(type.GetInterfaces(),
                           face => face == typeof(ITransformer));
                    if (findedFace != null)
                    {
                        TransformerTypes.Add(type);
                    }
                }
            }
        }

        public Assembly Assembly
        {
            get;
            private set;
        }

        protected IList<Type> TransformerTypes
        {
            get { return _TransformerTypes; }
        }

        public bool TryCreate(Type sourceType, out ITransformer result)
        {
            if (sourceType == null) throw new ArgumentNullException("sourceType");
            result = null;
            if (TransformerTypes.Contains(sourceType))
            {
                result = (ITransformer)Activator.CreateInstance(sourceType);
                return true;
            }
            return false;
        }
    }

}
